<?php
/**
 * DRM系统对接公用抽象方法
 * Author: 陈波(bo.chen@starcor.cn)
 * Date: 2015/3/30 19:45
 */
include_once dirname(dirname(dirname(__FILE__))) . "/common/v2/global.include.php";
//include_once dirname(dirname(__FILE__)).'/vcas/admin.class.php';
class common
{
	//DRM厂商
	private static  $drm_vendor = array();
	//DRM开关
	private static $drm_enable = 0;
	//WSDL 地址
	public static $wsdl = '';
	//WSDL连接对象
	public static $client = '';
	//DC对象
	private static $dc = '';
	//日志DC对象
	private static $log_dc = '';
	//VCAS 开关
	public static $vcas_enable = '';
	//VCAS标记
	public static $vcas_tag = 'vcas';

	public function __construct($db_policy=NL_DB_WRITE)
	{

	}

	/**
	 * 获取VCAS开关是否开启
	 * @return int 0:关闭，1:开启
	 */
	public static function get_vcas_enable()
	{
		self::$drm_vendor = get_config_v2('g_drm_vendor');
		self::$drm_enable = get_config_v2('g_drm_enable');
		if(self::$drm_enable)
		{
			return isset(self::$drm_vendor['vcas'])?self::$drm_vendor['vcas']:0;
		}
		return 0;

	}

	/**
	 * 验证result返回结果
	 * @param $result
	 */
	public static function get_vcas_result($data)
	{
		if(empty($data))
		{
			nl_log_v2_error('common','SOAP返回结果为空');
			return false;
		}

		$data = json_decode(json_encode($data),true);
		return $data;


	}
	/**
	 * 验证result list返回结果
	 * @param $result
	 */
	public static function get_vcas_result_list($result_list)
	{

	}

	/**
	 * 获取SOAP对象
	 * @return bool|SOAPClient|string
	 */
	public static function get_soap_client($wsdl)
	{
		if(empty($wsdl))
		{
			return false;
		}


		if(class_exists('SOAPClient'))
		{
			$context = stream_context_create( array (
				'ssl' => array (
					'verify_peer' => false,
					'allow_self_signed' => true
				),
			));
			$options['stream_context'] = $context;
			//self::$client = new nusoap_client($wsdl,true);
			$client = new SoapClient($wsdl,$options);
		}
		if(is_object($client))
		{
			return $client;
		}
		return false;
	}

	public static function get_log_dc($db_policy=NL_DB_WRITE)
	{
		$log_dc_param = array();
		$log_dc_param['db_policy'] = $db_policy;
		$log_dc_param['cache_policy'] = NP_KV_CACHE_TYPE_MEMCACHE;
		$log_dc_param['delay_open_db'] = true;
		$log_dc_param['delay_open_cache'] = true;
		$log_dc = nl_get_log_dc($log_dc_param);
		$log_dc->open();
		return $log_dc;
	}

	public static function add_drm_log($params,$result,$module,$interface_name,$type)
	{
		include_once dirname(__FILE__).'/drm_log.class.php';
		//日志DB对象
		$log_dc = self::get_log_dc();
//		var_dump($log_dc);exit;
		//日志数据组装
		$log_data = array();
		$log_data['nns_drm_tag'] = $params['nns_drm_tag'];
		$log_data['nns_interface_name'] = $interface_name;
		$log_data['nns_from'] = 0;
		$log_data['nns_module'] = $module;
		$log_data['nns_type'] = $type;
		$log_data['nns_request_data'] = var_export($params,true);
		$log_data['nns_user_id'] = isset($params['nns_user_id'])?$params['nns_user_id']:'';
		$log_data['nns_device_id'] = isset($params['nns_device_id'])?$params['nns_device_id']:'';
		//接口处理状态
		if(isset($result['result']['resultCode']) && $result['result']['resultCode'] == 0)
		{

			$log_data['nns_status'] = 1;
			$log_data['nns_desc'] = $result['result']['resultText'];
		}elseif(isset($result['resultCode']) && $result['resultCode'] == 0)
		{
			$log_data['nns_status'] = 1;
			$log_data['nns_desc'] = $result['resultText'];
		}else
		{
			$log_data['nns_status'] = 0;
			$log_data['nns_desc'] = isset($result['result']['resultText'])?$result['result']['resultText']:$result['resultText'];
		}


		$log_data['nns_response_data'] = var_export($result,true);
		$log_data['nns_debug_backtrace'] = var_export(debug_backtrace(),true);
		//$log_data['nns_create_mic_time'] = time().self::_get_current_mic_time();
		$log_data['nns_create_mic_time'] = self::_get_current_mic_time();
		//添加日志
		$log_re = nl_m_drm_log::add($log_dc,$log_data);

		if($log_re['code'] != ML_STATE_OK)
		{
			nl_log_v2_error('DRM log','DRM日志添加失败,日志数据：'.var_export($log_data,true));
		}
	}
	/**
	 * 获取毫秒级别的时间戳
	 * @return time
	 */
	private static function _get_current_mic_time()
	{
		$str_mic_time=microtime(true);
		$arr_mic_time=explode('.',$str_mic_time);
		return str_pad($arr_mic_time[1], 4, 0, STR_PAD_LEFT);
	}

	/**
	 * 检查传入数据是否为空
	 * Author:陈波
	 * Date: 2015/3/30 10:27
	 * @param type $data 数据
	 * @param type $filed 需要检查的字段
	 */
	static public function check_params($data, $filed)
	{
		foreach ($filed as $key)
		{
			if (!isset($data[$key]) || (empty($data[$key]) && $data[$key] === ''))
			{
				return $key;
			}
		}

		return false;
	}

	/**
	 * VCAS 登陆
	 * Author: 陈波(bo.chen@starcor.cn)
	 * $params = array(  可以为空，如果为空从配置文件中获取对应的账号密码
	 * 		'nns_user_name'=>'登录用户名',
	 * 		'nns_password'=>'登录密码',
	 * )
	 */

	public static function vcas_login($params = array())
	{
		if (!is_array($params))
		{
			return get_logic_result(ML_STATE_PARAM_ERROR,"params format is wrong");
		}
		include_once dirname(dirname(__FILE__)).'/vcas/admin.class.php';
		//如果没有传入账号密码，直接从配置文件中获取
		if(!isset($params['nns_user_name']) || !isset($params['nns_password']))
		{
			$params['nns_user_name'] = get_config_v2('g_drm_vcas_manager_user_name');
			$params['nns_password'] = get_config_v2('g_drm_vcas_manager_password');
		}
		$service_url = get_config_v2('g_drm_vcas_admin_manager_service_url');
		if(empty($service_url))
		{
			nl_log_v2_error('nl_config','g_drm_vcas_admin_manager_service_url为空或者未配置');
			return false;
		}
		//SOAP对象
		$client = self::get_soap_client($service_url);
		//登录请求
		$result = nl_vcas_admin::login($client,$params);
		;
		//解析返回结果
		$data = self::get_vcas_result($result);
		//设置日志所属DRM厂商
		$params['nns_drm_tag'] = self::$vcas_tag;
		//添加日志
		self::add_drm_log($params,$data,'admin','signOn','login');
		//非0，认为失败
		if($data['result']['resultCode'] != 0)
		{
			nl_log_v2_error('nl_config','VCAS-login返回失败，返回参数:'.var_export($result,true));
			return false;
		}
		//定义返回结果
		$result = array();
		$result['session'] = $data['sessionHandle']['handle'];
		return $result;
	}


	/**
	 * VCAS注销
	 * Author: 陈波(bo.chen@starcor.cn)
	 * @param $dc
	 * @param $params
	 * @return array|void
	 */
	public static function vcas_logout($session)
	{
		if (empty($session))
		{
			return get_logic_result(ML_STATE_PARAM_ERROR,"params format is wrong");
		}

		$service_url = get_config_v2('g_drm_vcas_admin_manager_service_url');
		if(empty($service_url))
		{
			nl_log_v2_error('nl_config','g_drm_vcas_admin_manager_service_url为空或者未配置');
			return false;
		}
		//SOAP对象
		$client = self::get_soap_client($service_url);

		include_once dirname(dirname(__FILE__)).'/vcas/admin.class.php';
		$user = new stdClass();
		$user->handle = $session;
		//DRM注销接口
		$result = nl_vcas_admin::logout($client,$user);
		//解析DRM返回结果
		$data = self::get_vcas_result($result);
		//日志所属DRM厂商
		$params['nns_drm_tag'] = self::$vcas_tag;
		//添加日志
		self::add_drm_log($params,$data,'admin','signOff','logout');
		//非0，认为失败
		if($data['resultCode'] != 0)
		{
			nl_log_v2_error('common','VCAS-logout失败，请求参数:'.var_export($user,true).'，返回数据：'.var_export($result,true));
			return false;
		}
		nl_log_v2_error('common','VCAS-logout成功，请求参数:'.var_export($user,true));
		return true;

	}
}